package com.xgh.offer;

import com.xgh.TreeNode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @ClassName Offer32
 * @Description
 * @Author xinggh
 * @Date 2020/7/1 21:30
 * @Version 1.0
 **/
public class Offer32 {
    /**
     * 剑指 Offer 32 - II. 从上到下打印二叉树 II
     * 从上到下按层打印二叉树，同一层的节点按从左到右的顺序打印，每一层打印到一行。
     * <p>
     * <p>
     * <p>
     * 例如:
     * 给定二叉树: [3,9,20,null,null,15,7],
     * <p>
     * 3
     * / \
     * 9  20
     * /  \
     * 15   7
     * 返回其层次遍历结果：
     * <p>
     * [
     * [3],
     * [9,20],
     * [15,7]
     * ]
     */

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList();

        if (root == null) {
            return result;
        }

        Deque<TreeNode> deque = new LinkedList();
        deque.add(root);

        while (!deque.isEmpty()) {
            List list = new ArrayList();
            int c = deque.size();
            for (int i = 0; i < c; i++) {
                TreeNode pop = deque.pop();
                list.add(pop.val);
                if (pop.left != null) {
                    deque.add(pop.left);
                }
                if (pop.right != null) {
                    deque.add(pop.right);
                }

            }
            result.add(list);
        }

        return result;
    }
}
